<?php

namespace App\Task;

use App\Model\FlyOrder;
use App\Model\FlyPayOrder;
use App\Service\FlyOrderService;
use App\Service\OrderCouponService;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;

class OrderCancelTask
{


    public function execute(): void
    {
        Db::beginTransaction();
        try {
            $orders = FlyPayOrder::query()
                ->where(['is_pay' => 0, 'paid_price' => 0, 'is_close' => 0, 'delete_time' => 0])
                ->where('create_time', '<=', time() - 86400 * 2)
                ->pluck('pay_order_id');
            $orders = empty($orders) ? [] : $orders->toArray();
            // 取消支付单
            $userCoupon = new OrderCouponService();
            if (!empty($orders)) {
                FlyPayOrder::whereIn('pay_order_id', $orders)->update(['is_close' => 1, 'close_time' => time(), 'close_reason' => '超时未支付']);
                // 取消商家订单
                FlyOrder::whereIn('pay_order_id', $orders)->update(['order_status' => FlyOrderService::STATUS_CLOSED, 'close_time' => time(), 'cancel_remark' => '超时未支付']);
                $coupon_check = FlyOrder::whereIn('pay_order_id', $orders)->select(['order_id', 'coupon_id', 'user_id'])->get()->toArray();
                foreach ($coupon_check as $coupon) {
                    // 返还用户优惠券
                    if ($coupon['coupon_id'] > 0) {
                        $re = $userCoupon->useUserCoupon($coupon['user_id'], $coupon['coupon_id'], $coupon['order_id']);
                        if (!$re) {
                            Db::rollBack();
                            break;
                        }
                    }
                }
            }
        } catch (\Throwable $exception) {
            echo $exception->getMessage();
            Db::rollBack();
        }
        Db::commit();
    }
}